<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close @closed="$emit('closed')" align-center :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="150" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item :label="$t('procure.apply.name')" prop="apply_id">
                        <el-select v-model="form.apply_id" :placeholder="$t('all.select')" filterable>
                            <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('procure.order.purchaser')" prop="purchase_staff">
                        <el-select v-model="form.purchase_staff" filterable clearable :placeholder="$t('all.select')" style="width:100%">
                            <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('sale.sale.date')" prop="open_date">
                        <el-date-picker v-model="form.open_date" type="date" :placeholder="$t('all.select')" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('goods.goods.ware')" prop="ware_id">
                        <el-select v-model="form.ware_id" filterable style="width: 100%" :placeholder="$t('all.select')" @change="wareChange" clearable>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item :label="$t('sale.sale.isticket')" prop="is_ticket">
                        <el-select v-model="form.is_ticket" filterable clearable :placeholder="$t('all.select')" style="width:100%">
                            <el-option :label="$t('all.selectno')" :value="1"/>
                            <el-option :label="$t('all.selectyes')" :value="2"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('sale.sale.istax')" prop="is_tax">
                        <el-select v-model="form.is_tax" filterable clearable :placeholder="$t('all.select')" style="width:100%">
                            <el-option :label="$t('all.selectno')" :value="0"/>
                            <el-option :label="$t('all.selectyes')" :value="1"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-col :span="12">
                <el-form-item :label="$t('all.remark')" prop="remark">
                    <el-input v-model="form.remark" :placeholder="$t('all.enter')" type="textarea" clearable></el-input>
                </el-form-item>
            </el-col>
            <el-form-item :label="$t('procure.order.orderlist')" prop="detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct">{{$t ('goods.bom.select')}}</el-button>
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkPlan">{{$t('procure.order.select')}}</el-button>
                <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" :placeholder="$t('all.noData')" height="350" hideAdd show-summary>
                    <el-table-column :label="$t('goods.goods.name')" align="center">
                        <template #default="scope">
                            {{scope.row.goods_name}}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('goods.goods.code')" align="center">
                        <template #default="scope">
                            {{scope.row.goods_code}}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('goods.unit.unit')" align="center">
                        <template #default="scope">
                            {{scope.row.unit_name}}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.number')" prop="number" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.number" :placeholder="$t('all.number')" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.price')" prop="price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.price" :placeholder="$t('all.price')" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.subtotal')" prop="total_price" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.total_price" :placeholder="$t('all.subtotal')" readonly></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('all.remark')" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" :placeholder="$t('all.remark')"></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-form-item :label="$t('all.attachment')" prop="enclosure">
                <sc-upload-file v-model="form.enclosure" :limit="1">
                    <el-button type="primary" icon="el-icon-upload">{{$t('all.selectattachment')}}</el-button>
                </sc-upload-file>
            </el-form-item>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item :label="$t('procure.order.allmoney')" prop="total_price">
                        <el-input v-model="form.total_price" :placeholder="$t('procure.order.allmoney')" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('finance.account')" prop="settlement_id">
                        <el-select v-model="form.settlement_id" filterable clearable :placeholder="$t('all.select')" style="width:100%">
                            <el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('finance.receivemoney')" prop="pay_price">
                        <el-input v-model="form.pay_price" :placeholder="$t('finance.receivemoney')" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('procure.order.stage')" prop="is_stages">
                        <el-switch v-model="form.is_stages" :active-value="1" :inactive-value="0" inline-prompt :active-text="$t('procure.order.isstage')" :inactive-text="$t('procure.order.unstage')"></el-switch>
                        <!-- <el-button v-if="form.is_stages == 1" size="small" type="primary" @click="openStage">设置付款金额</el-button> -->
                        <el-tag type="primary" v-if="form.is_stages == 1" @click="openStage">{{$t('procure.order.setstag')}}</el-tag>
                    </el-form-item>
                </el-col>
            </el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >{{$t('all.cancel')}}</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">{{$t('all.save')}}</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(1)">{{$t('all.savecheck')}}</el-button>
		</template>
	</el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
    <select-plan v-if="dialog.plan" ref="planDialog" @success="planUpdate" @closed="dialog.plan=false"></select-plan>
    <el-dialog :title="$t('procure.order.setstag')" v-model="stage" :close-on-click-modal="false" :close-on-press-escape="false">
        <sc-form-table ref="table" v-model="stages_all" :addTemplate="addTemplate" :placeholder="$t('all.noData')" height="450" hideAdd hideDelete>
            <el-table-column prop="type" :label="$t('procure.order.stagetype')" align="center" width="150">
                <template #default="scope">
                    <div v-for="item in stages_all" :key="item.stages_number">
                        {{ scope.row.stages_number == item.stages_number ? item.type : '' }}
                    </div>
                </template>
            </el-table-column>s
            <el-table-column :label="$t('procure.order.percentage')" prop="collect_rate" align="center">
                <template #default="scope">
                    <el-input-number type="number" v-model="scope.row.collect_rate" :placeholder="$t('procure.order.percentage')" @change="stageInputRate(scope.row,scope.$index)" controls-position="right">
                        <template #suffix>
                            <span>%</span>
                        </template>
                    </el-input-number>
                </template>
            </el-table-column>
            <el-table-column :label="$t('finance.receivemoney')" prop="money" align="center">
                <template #default="scope">
                    <el-input-number type="number" v-model="scope.row.money" :placeholder="$t('finance.receivemoney')" @change="stageInput(scope.row,scope.$index)" controls-position="right"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column :label="$t('procure.order.date')" prop="collect_date" align="center">
                <template #default="scope">
                    <el-date-picker v-model="scope.row.collect_date" type="date" :placeholder="$t('all.select')" :value-format="'YYYY-MM-DD'" style="width:100%" />
                </template>
            </el-table-column>
            <el-table-column :label="$t('all.remark')" prop="remark" align="center">
                <template #default="scope">
                    <el-input v-model="scope.row.remark" :placeholder="$t('all.remark')"></el-input>
                </template>
            </el-table-column>
        </sc-form-table>
        <template #footer>
            <el-button @click="stage = false">{{$t('all.cancel')}}</el-button>
            <el-button type="primary" @click="closeStage">{{$t('all.confirm')}}</el-button>
        </template>
    </el-dialog>
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';
import SelectPlan from '../plan/selectPlan.vue';
	export default {
        components: { selectGoods, SelectPlan },
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
                    add: this.$t('all.add'),
                    copy: this.$t('all.add'),
                    edit: this.$t('all.edit'),
                    show: this.$t('all.show')
				},
				visible: false,
				isSaveing: false,
				form: {
					id:"",
					code: "",
					apply_id: "",
					purchase_staff: "",
					open_date: this.moment().format('YYYY-MM-DD'),
					is_ticket: "",
					is_tax: "",
					remark: "",
					enclosure: "",
					settlement_id: "",
					pay_price: 0,
					total_price: "",
                    detail:[],
                    ware_id: "",
                    is_stages: 0,
                    stages_all: [],
                    is_check: 0
				},
                stage: false,
                stages_all: [
                    {
                        stages_number: 1,
                        type: this.$t('procure.order.type1'),
                        collect_rate: 100,
                        money: 0,
                        collect_date: this.moment().format('YYYY-MM-DD'),
                        remark: ""
                    },
                    {
                        stages_number: 2,
                        type: this.$t('procure.order.type2'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 3,
                        type: this.$t('procure.order.type3'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 4,
                        type: this.$t('procure.order.type4'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 5,
                        type: this.$t('procure.order.type5'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 6,
                        type: this.$t('procure.order.type6'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 7,
                        type: this.$t('procure.order.type7'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 8,
                        type: this.$t('procure.order.type8'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 9,
                        type: this.$t('procure.order.type9'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 10,
                        type: this.$t('procure.order.type10'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 11,
                        type: this.$t('procure.order.type11'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 12,
                        type: this.$t('procure.order.type12'),
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                ],
                rules: {
					apply_id: [
						{required: true, message: this.$t('all.select') + ' ' + this.$t('procure.apply.apply')}
					],
                    ware_id: [
						{required: true, message: this.$t('all.select') + ' ' + this.$t('ware.ware')}
					],
                    purchase_staff: [
						{required: true, message: this.$t('all.select') + ' ' + this.$t('procure.order.purchaser')}
					],
                    is_tax: [
						{required: true, message: this.$t('all.select') + ' ' + this.$t('sale.sale.istax')}
					],
                    is_ticket: [
						{required: true, message: this.$t('all.select') + ' ' + this.$t('sale.sale.isticket')}
					],
				},
                addTemplate:{},
                dialog: {
                    goods: false,
                    plan: false,
                },
                applyList: [],
                adminList: [],
                accountList: [],
                wareList: [],
			}
		},
		mounted() {
            this.getApply();
            this.getUser()
            this.getAccount()
            this.getWare()
            this.getMonth()
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			//表单提交方法
			submit(e){
                this.form.is_check = e
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res  = [];
                        if (this.form.id) {
                            res = await this.$API.procure.order.edit.post(this.form);
                        }else{
                            res = await this.$API.procure.order.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if(res!=''){
                            if(res.code == 1){
                                this.visible = false;
                                this.$emit('success', this.form, this.mode)
                                this.$message.success(this.$t('all.yes'))
                            }else{
                                this.$alert(res.message,this.$t('all.prompt'), {type: "error"});
                            }
                        }
                    }
                })
			},
			//表单注入数据
			async setData(data){
				this.form.id = data.id
                var res = await this.$API.procure.order.detail.get({id:data.id});
                this.form.code = res.data.code
                this.form.apply_id = res.data.apply_id
                this.form.ware_id = res.data.ware_id
                this.form.purchase_staff = res.data.purchase_staff
                this.form.open_date = res.data.open_date
                this.form.is_ticket = res.data.is_ticket
                this.form.is_tax = res.data.is_tax
                this.form.remark = res.data.remark
                this.form.enclosure = res.data.enclosure
                this.form.total_price = res.data.total_price
                this.form.settlement_id = res.data.settlement_id
                this.form.pay_price = res.data.pay_price
                let array = []
                res.data.detail.map(item=>{
                    array.push({
                        id:item.id,
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        unit_name:item.goods && item.goods.unit && item.goods.unit.unit_name,
                        goods_code:item.goods && item.goods.goods_code,
                        number:item.number,
                        price:item.price,
                        total_price:item.total_price,
                        remark:item.remark,
                    })
                })
                this.form.detail = array
                this.form.is_stages = res.data.is_stages
				if(res.data.is_stages == 1) {
					let stage = res.data.by_stages && res.data.by_stages
					for (let i = 0; i < stage.length; i++) {
						stage[i].type = this.stages_all[i].type
						this.stages_all.splice(i, 1, stage[i]);
					}
				}
			},
            // 选择产品
            checkProduct(){
                this.dialog.goods = true
                this.$nextTick(() => {
                    this.$refs.goodsDialog.open('add')
                })
            },
            checkPlan(){
                this.dialog.plan = true
                this.$nextTick(() => {
                    this.$refs.planDialog.open('add')
                })
            },
            // 选择产品返回
            goodsUpdate(data){
                let array = []
                data.map((item)=>{
                    array.push({
                        goods_id:item.id,
                        goods_name:item.goods_name,
                        unit_name:item.unit && item.unit.unit_name,
                        goods_code:item.goods_code,
                        number:1,
                        price:item.cost_price,
                        total_price:item.cost_price,
                    })
                })
                let existingIds = this.form.detail.map(item => item.goods_id);
                for(let i = array.length - 1; i >= 0; i--){
                    if(existingIds.includes(array[i].goods_id)){
                        array.splice(i, 1);
                    }
                }
                this.form.detail = [...this.form.detail,...array]
                this.totalCompute()
            },
            planUpdate(data){
                let array = []
                data.map((item)=>{
                    array.push({
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        unit_name:item.goods && item.goods.unit.unit_name,
                        goods_code:item.goods && item.goods.goods_code,
                        number:item.plan_num,
                        price:item.price,
                        total_price: (Number(item.plan_num) * Number(item.price)).toFixed(2)
                    })
                })
                let existingIds = this.form.detail.map(item => item.goods_id);
                for(let i = array.length - 1; i >= 0; i--){
                    if(existingIds.includes(array[i].goods_id)){
                        array.splice(i, 1);
                    }
                }
                this.form.detail = [...this.form.detail,...array]
                this.totalCompute()
            },
            // 供应商列表
            async getApply(){
                var res = await this.$API.apply.apply.all.get();
                this.applyList = res.data
            },
            // 获取采购人
            async getUser(){
                var res = await this.$API.system.admin.all.get();
                this.adminList = res.data;
            },
            // 账户
            async getAccount(){
                var res = await this.$API.finance.account.all.get();
                this.accountList = res.data;
            },
            // 获取仓库
            async getWare(){
                var res = await this.$API.goods.ware.all.get();
                this.wareList = res.data;
                if(this.mode == 'add'){
                    res.data.map(item=>{
                        if(item.is_default == 1){
                            this.form.ware_id = item.id
                        }
                    })
                }
            },
            onFocus(event){
                event.target.select();
            },
            totalCompute() {
                this.form.total_price = 0
                let count_price = 0
                this.form.detail.map(item => {
                    if(item.price && item.number){
                        item.total_price = (Number(item.number) * Number(item.price)).toFixed(2)
                        count_price = Number(count_price) + (Number(item.number) * Number(item.price))
                    }
                })
                this.form.total_price = (count_price).toFixed(2)
            },
            getMonth(){
                for (let i = 1; i < this.stages_all.length; i++) {
                    let prevDate = this.moment(this.stages_all[i - 1].collect_date);
                    let nextDate = prevDate.add(1, 'month');
                    this.stages_all[i].collect_date = nextDate.format('YYYY-MM-DD');
                }
            },
            stageInput(row,index) {
                // this.setStage(row,index)
                let num = 0
                this.stages_all.map((item,index1)=>{
                    if(index1 <= index){
                        num +=item.money
                    }
                    if(index1 == index + 1){
                        item.money = this.form.total_price - Number(num)
                    }
                })
            },
            setStage(row,index){
                let num = 0
                this.stages_all.map((item,index1)=>{
                    if(index1 <= index){
                        num +=item.money
                    }
                    if(index1 == index + 1){
                        item.money = this.form.total_price - Number(num)
                    }
                })
            },
            stageInputRate(row,index) {
                let num = 0
                this.stages_all.map((item,index1)=>{
                    if(index1 <= index){
                        num +=item.collect_rate
                        item.money = (this.form.total_price * num / 100).toFixed(2)
                    }
                    if(index1 == index + 1){
                        item.collect_rate = 100 - Number(num)
                        // item.money = Number(this.form.total_price) * Number(item.collect_rate) / 100
                    }
                })
            },
            closeStage(){
                this.stage = false
                let array = []
                this.stages_all.map(item=>{
                    if(item.money!=0){
                        array.push({
                            collect_rate:item.collect_rate,
                            money:item.money,
                            stages_number:item.stages_number,
                            collect_date:item.collect_date,
                            remark:item.remark,
                        })
                    }
                })
                this.form.stages_all = array
            },
            openStage(){
                this.stage = true
                if(this.mode == 'add'){
                    this.stages_all[0].money = this.form.total_price
                }
            },
            async setCopy(data){
                var res = await this.$API.procure.order.detail.get({id:data.id});
                this.form.apply_id = res.data.apply_id
                this.form.ware_id = res.data.ware_id
                this.form.purchase_staff = res.data.purchase_staff
                this.form.open_date = res.data.open_date
                this.form.total_price = res.data.total_price
                this.form.settlement_id = res.data.settlement_id
                this.form.pay_price = res.data.pay_price
                let array = []
                res.data.detail.map(item=>{
                    array.push({
                        id:item.id,
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        unit_name:item.goods && item.goods.unit && item.goods.unit.unit_name,
                        goods_code:item.goods && item.goods.goods_code,
                        number:item.number,
                        price:item.price,
                        total_price:item.total_price,
                        remark:item.remark,
                    })
                })
                this.form.detail = array
			},
		}
	}
</script>

<style>
</style>
